import {Component, OnInit} from '@angular/core';
import {NzImageService} from 'ng-zorro-antd/image';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzModalService} from 'ng-zorro-antd/modal';
import {AssessPriceService} from '../../assess-price.service';
import {LoveRecycManageService} from '../../love-recyc-manage.service';
import {ActivatedRoute, Router} from '@angular/router';
import {PreviewOptionImgRemarkComponent} from '../preview-option-img-remark/preview-option-img-remark.component';
import {JSON} from 'tinymce';

interface CUSTOMMODAL {
  visible: boolean;
  title: string;
  groupIndex: number;
  groupItemIndex: any;
  optionRelations: any[];
  usedPriceInfo: any;
  newPriceInfo: any;
}

@Component({
  selector: 'app-assess-type-manage',
  templateUrl: './assess-type-manage.component.html',
  styleUrls: ['./assess-type-manage.component.scss']
})
export class AssessTypeManageComponent implements OnInit {
  // 是否已经保存
  isSaved = false;
  // 页面是否是只读
  readonly = false;
  // 基础数据
  formData = {
    evalStatus: 0,
    brand: '',
    brandName: '',
    department: '',
    departmentName: '',
    type: '',
    evaluationId: '',
    typeName: '',
    template: '',
    templateName: '',
    remark: '',
    usedBasePrice: 0,
    newBasePrice: 0,
  };
  // 待选模版列表
  templateOptions: any[] = [];
  // 品牌列表
  brandOptions: any[] = [];
  // 系列列表
  departmentOptions: any[] = [];
  // 机型列表
  typeOptions: any[] = [];
  // 选中的题目列表
  questionList: any[] = [];
  // 特殊设置列表
  customList: any[] = [];
  checkedIds: any[] = [];
  baseQuestion: any = {
    questionId: '',
    options: []
  };
  cacheData: any;
  currentOId = '';
  // 已经被联动改变的特殊设置序号列表
  modifyCustomOptionColor: any[] = [];
  selectedCustom: any = {};
  selectedFixedPrice: any = {};
  // 选项关联的价格
  optionsRelationPrice: any;
  // 选项描述
  optionRemark = {
    visible: false,
    title: '',
    option: {
      optionName: '',
      optionRemark: '',
      optionImages: [],
    },
  };
  // 预览模态框显隐
  previewAssessTypeVisible = false;
  // 是否是准新机
  isNewDevice = false;
  // 评估结果
  assessPriceText = '';
  // 一口价评估结果
  fixedPriceText = '';

  // 一口价列表
  fixedPriceList: any[] = [];
  // 一口价模态框
  fixedPriceModal: any = {
    visible: false,
    title: '',
    optionRelations: [{questionId: '', optionId: ''}, {questionId: '', optionId: ''}],
    usedPriceInfo: {type: 'percentage', price: 0},
    newPriceInfo: {type: 'percentage', price: 0},
    editIndex: null,
  };
  // 特殊设置模态框
  customModal: CUSTOMMODAL = {
    visible: false,
    title: '',
    groupIndex: 0,
    groupItemIndex: null,
    optionRelations: [{questionId: '', optionId: ''}, {questionId: '', optionId: ''}],
    usedPriceInfo: {type: 'percentage', price: 0},
    newPriceInfo: {type: 'percentage', price: 0}
  };
  optionPriceModal = {
    visible: false,
    modifyCustom: false,
    modifyCustomPercentage: 70,
    optionId: '',
    usedPriceInfo: {type: 'percentage', price: 0},
    newPriceInfo: {type: 'percentage', price: 0}
  };
  // 复制价格逻辑
  copyOptionModal = {
    visible: false,
    optionId: ''
  };
  // 一口价估价结果
  fixedPriceResult = {isFixedPrice: false, price: 0};
  questionNameList: any;
  optionNameList: any;
  // 保底价和基准价
  mABP = {
    checked: false,
    minPrice: 0,
    basePrice: 0
  };
  operationType = '';
  formatterPercent = (value: number): string => `${value}%`;
  parserPercent = (value: string): string => value.replace('%', '');

  constructor(
    private nzImageService: NzImageService,
    private message: NzMessageService,
    private nzModalService: NzModalService,
    private assessPriceService: AssessPriceService,
    private loveRecycManageService: LoveRecycManageService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
  ) {
  }

  ngOnInit(): void {
    this.setInitData();
    // this.cacheData = assessData;
    // console.log(assessData);
  }

  async setInitData() {
    await this.assessPriceService.getTemplateOptions().then((res: any) => {
      if (res.code === 0) {
        this.templateOptions = res.data;
      }
    });
    await this.loveRecycManageService.getRecycleBrandList({page: 1, pageSize: 9999}).then(async (res: any) => {
      if (res.code === 0) {
        this.brandOptions = res.data.records;
      }
    });
    this.operationType = this.activatedRoute.snapshot.queryParams.operationType;
    if (this.operationType === 'modify') {
      this.initModifyData();
    }
    if (this.operationType === 'view') {
      this.readonly = true;
      this.initModifyData();
    }
    if (this.operationType === 'verifyView') {
      this.readonly = true;
      await this.initModifyData();
      this.questionList.forEach((question: any) => {
        if (question.selectType === 0) {
          question.options.forEach((option: any) => {
            if (this.activatedRoute.snapshot.queryParams.optionIds.includes(option.id + '')) {
              option.value = option.id;
            }
          });
        } else if (question.selectType === 1) {
          // 遍历多选选项
          question.options.forEach((option: any) => {
            if (this.activatedRoute.snapshot.queryParams.optionIds.includes(option.id + '')) {
              option.check = true;
            }
          });
        }
      });
      this.calcPrice();
    }
  }

  // 初始化修改数据
  async initModifyData() {
    const data = JSON.parse(this.activatedRoute.snapshot.queryParams.assessTypeInfo);
    console.log(data);
    this.formData.brand = data.brandId;
    this.loveRecycManageService.getRecycleSeriesList({brandId: data.brandId, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.departmentOptions = res.data.records;
      }
    });
    this.formData.department = data.seriesId;
    this.loveRecycManageService.getRecycleModelList({seriesId: data.seriesId, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
    this.formData.type = data.id;
    this.formData.remark = data.remarks;
    this.formData.template = data.evalId;
    this.formData.evalStatus = data.evalStatus;
    this.formData.evaluationId = data.evaluationId;
    this.formData.newBasePrice = data.newPrice;
    this.formData.usedBasePrice = data.secondHandPrice;
    this.cacheData = {
      evalId: data.evalId, ...JSON.parse(data.modelContext)
    };
    this.currentOId = this.cacheData.baseQuestion.options[0].id;
    await this.setQuestionList(data.evalId);
    // this.currentOId = this.cacheData.baseQuestion.options[0].id;
    // this.optionsRelationPrice = this.cacheData.baseQuestion.options[0].questionRelation;
    // this.customList = this.cacheData.baseQuestion.options[0].customList;
    // this.fixedPriceList = this.cacheData.baseQuestion.options[0].fixedPrice || [];
    // this.optionsRelationPrice = JSON.parse(data.modelContext).questionRelation;
    // this.customList = JSON.parse(data.modelContext).customList;
    // this.baseQuestion = JSON.parse(data.modelContext).baseQuestion || {questionId: '', options: []};
    // this.fixedPriceList = JSON.parse(data.modelContext).fixedPrice || [];
  }

  setCacheData(evalId: any, questionId: any) {
    if (!this.cacheData) {
      return;
    }
    const cacheData = JSON.parse(JSON.stringify(this.cacheData));
    if (evalId && cacheData.evalId === evalId
      || this.formData.template === cacheData.evalId && questionId && cacheData.baseQuestion.questionId === questionId) {
      this.baseQuestion = cacheData.baseQuestion;
      this.currentOId = this.baseQuestion.options[0].id;
      this.optionsRelationPrice = this.baseQuestion.options[0].questionRelation || {};
      this.customList = this.baseQuestion.options[0].customList;
      this.fixedPriceList = this.baseQuestion.options[0].fixedPrice || [];
      this.modifyCustomOptionColor = [];
    }
  }

  baseQuestionOptionClick(oId: any) {

    this.baseQuestion.options.forEach((o: any) => {
      if (o.id === this.currentOId) {
        o.customList = this.customList;
        o.questionRelation = this.optionsRelationPrice;
        o.fixedPrice = this.fixedPriceList;
      }
    });
    if (this.cacheData) {
      this.cacheData.baseQuestion = this.baseQuestion || {
        questionId: '',
        options: []
      };
    } else {
      this.cacheData = {
        evalId: this.formData.template,
        baseQuestion: this.baseQuestion || {
          questionId: '',
          options: []
        }
      };
    }

    this.currentOId = oId;
    this.modifyCustomOptionColor = [];
    this.questionList.forEach((item: any) => {
      if (item.selectType === 0) {
        item.options.forEach((o: any) => {
          o.value = '';
        });
      }
      if (item.selectType === 1) {
        item.options.forEach((o: any) => {
          o.check = false;
        });
      }
    });
    this.fixedPriceResult = {isFixedPrice: false, price: 0};
    this.assessPriceText = '';
    this.selectedCustom = {};
    this.selectedFixedPrice = {};
    if (!this.cacheData) {
      return;
    }
    const cacheData = JSON.parse(JSON.stringify(this.cacheData));
    cacheData.baseQuestion.options.forEach((o: any) => {
      if (o.id === oId) {
        if (o.questionRelation) {
          this.optionsRelationPrice = o.questionRelation;
        } else {
          this.initOptionsRelationPrice(this.questionList);
        }
        this.customList = o.customList || [];
        this.fixedPriceList = o.fixedPrice || [];
      }
    });
  }

  // 设置系列待选项
  setDepartmentOptions(id: any) {
    this.typeOptions = [];
    this.formData.type = '';
    this.departmentOptions = [];
    this.formData.department = '';
    if (!id) {
      return;
    }
    this.loveRecycManageService.getRecycleSeriesList({brandId: id, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.departmentOptions = res.data.records;
      }
    });
  }

  // 设置机型待选项
  setTypeOptions(id: any) {
    this.typeOptions = [];
    this.formData.type = '';
    if (!id) {
      return;
    }
    this.loveRecycManageService.getRecycleModelList({seriesId: id, page: 1, pageSize: 9999}).then((res: any) => {
      if (res.code === 0) {
        this.typeOptions = res.data.records;
      }
    });
  }

  // 初始化选项的价格数据
  initOptionsRelationPrice(list: any[]) {
    this.optionsRelationPrice = {};
    list.forEach((q: any) => {
      q.options.forEach((o: any) =>
        this.optionsRelationPrice = {
          ...this.optionsRelationPrice,
          [o.id]: {usedPriceInfo: {type: 'percentage', price: 0}, newPriceInfo: {type: 'percentage', price: 0}}
        }
      );
    });
  }

  // 题目id转名称
  questionIdToName(id: string, questionList: any[]) {
    let result = id === 'end' ? '结束' : 'id转名称异常';
    questionList.forEach((q: any, index) => {
      if (q.id === id) {
        result = q.questionName;
      }
    });
    return result;
  }

  // 选项id转名称
  optionIdToName(id: string) {
    let name = '';
    this.questionList.forEach((q: any) => {
      if (q.id === this.baseQuestion.questionId) {
        q.options.forEach((o: any) => {
          if (o.id === id) {
            name = o.optionName;
          }
        });
      }
    });
    return name;
  }

  // 选项id转题目名称+选项名称
  optionIdToQAndOName(id: string) {
    let name = '';
    this.questionList.forEach((q: any) => {
      q.options.forEach((o: any) => {
        if (o.id === id) {
          name = q.questionName + '>' + o.optionName;
        }
      });
    });
    return name;
  }

  // 显示选项价格编辑框
  showOptionPriceModal(optionId: any) {
    this.optionPriceModal = {
      visible: true,
      modifyCustom: false,
      modifyCustomPercentage: 70,
      optionId,
      usedPriceInfo: {
        type: this.optionsRelationPrice[optionId].usedPriceInfo.type,
        price: this.optionsRelationPrice[optionId].usedPriceInfo.price
      },
      newPriceInfo: {
        type: this.optionsRelationPrice[optionId].newPriceInfo.type,
        price: this.optionsRelationPrice[optionId].newPriceInfo.price
      }
    };
  }

  setBaseQuestion(id: any) {
    if (!id) {
      this.currentOId = '';
    }
    this.baseQuestion.options = [];
    this.questionList.forEach(q => {
      if (q.id === id) {
        this.baseQuestion.options = q.options.map((o: any) => {
          return {
            id: o.id,
            usedPriceInfo: {
              basePrice: 0,
              type: 'percentage',
              price: 0
            },
            newPriceInfo: {
              basePrice: 0,
              type: 'percentage',
              price: 0
            }
          };
        });
        this.currentOId = this.baseQuestion.options[0].id;
      }
    });
    this.questionList.forEach((item: any) => {
      if (item.selectType === 0) {
        item.options.forEach((o: any) => {
          o.value = '';
        });
      }
      if (item.selectType === 1) {
        item.options.forEach((o: any) => {
          o.check = false;
        });
      }
    });

    this.fixedPriceResult = {isFixedPrice: false, price: 0};
    this.assessPriceText = '';
    this.selectedCustom = {};
    this.selectedFixedPrice = {};
    this.cacheData = {};
    this.customList = [];
    this.fixedPriceList = [];
    this.initOptionsRelationPrice(this.questionList);
    // this.setCacheData('', id);
  }

  saveOptionPriceModal() {
    if (this.optionPriceModal.usedPriceInfo.price === null || !this.optionPriceModal.usedPriceInfo.price.toString().length) {
      this.message.warning('请输入二手扣钱信息');
      return;
    }
    if (this.optionPriceModal.newPriceInfo.price === null || !this.optionPriceModal.newPriceInfo.price.toString().length) {
      this.message.warning('请输入准新扣钱信息');
      return;
    }
    if (this.optionPriceModal.modifyCustom) {
      if (this.optionsRelationPrice[this.optionPriceModal.optionId].usedPriceInfo.type === this.optionPriceModal.usedPriceInfo.type
        && this.optionPriceModal.usedPriceInfo.type === 'percentage') {
        this.customList.forEach((c: any, cIndex: number) => {
          c.forEach((o: any, oIndex: number) => {
            o.optionRelations.forEach((r: any) => {
              if (this.optionPriceModal.optionId === r.optionId) {
                this.modifyCustomOptionColor.push(cIndex + '-' + oIndex);
                o.usedPriceInfo.price +=
                  (this.optionPriceModal.usedPriceInfo.price
                    - this.optionsRelationPrice[this.optionPriceModal.optionId].usedPriceInfo.price)
                  * this.optionPriceModal.modifyCustomPercentage / 100;
                o.usedPriceInfo.price = o.usedPriceInfo.price > 0 ? o.usedPriceInfo.price : 0;
              }
            });
          });
        });
      }
      if (this.optionsRelationPrice[this.optionPriceModal.optionId].newPriceInfo.type === this.optionPriceModal.newPriceInfo.type
        && this.optionPriceModal.newPriceInfo.type === 'percentage') {
        this.customList.forEach((c: any, cIndex: number) => {
          c.forEach((o: any, oIndex: number) => {
            o.optionRelations.forEach((r: any) => {
              if (this.optionPriceModal.optionId === r.optionId) {
                this.modifyCustomOptionColor.push(cIndex + '-' + oIndex);
                o.newPriceInfo.price +=
                  (this.optionPriceModal.newPriceInfo.price
                    - this.optionsRelationPrice[this.optionPriceModal.optionId].newPriceInfo.price)
                  * this.optionPriceModal.modifyCustomPercentage / 100;
                o.newPriceInfo.price = o.newPriceInfo.price > 0 ? o.newPriceInfo.price : 0;
              }
            });
          });
        });
      }
    }
    this.optionsRelationPrice[this.optionPriceModal.optionId].usedPriceInfo.type = this.optionPriceModal.usedPriceInfo.type;
    this.optionsRelationPrice[this.optionPriceModal.optionId].usedPriceInfo.price = this.optionPriceModal.usedPriceInfo.price;
    this.optionsRelationPrice[this.optionPriceModal.optionId].newPriceInfo.type = this.optionPriceModal.newPriceInfo.type;
    this.optionsRelationPrice[this.optionPriceModal.optionId].newPriceInfo.price = this.optionPriceModal.newPriceInfo.price;
    this.hideOptionPriceModal();
  }

  // 改变联动的特殊设置的背景色
  changeMCOC(a: number, b: number) {
    return this.modifyCustomOptionColor.includes(a + '-' + b) ? 'rgba(255,0,0,.1)' : '';
  }

  // 隐藏选项价格编辑框
  hideOptionPriceModal() {
    this.optionPriceModal = {
      visible: false,
      modifyCustom: false,
      modifyCustomPercentage: 70,
      optionId: '',
      usedPriceInfo: {type: 'percentage', price: 0},
      newPriceInfo: {type: 'percentage', price: 0}
    };
  }

  // 显示选项描述和图片
  showOptionRemarkModal(question: any, option: any) {
    let details: any[] = [];
    question.options.forEach((o: any) => {
      if (o.optionImages || o.optionRemark) {
        details = [...details, ...o.optionImages.split(',').map((v: any) => ({
          id: o.id,
          name: o.optionName,
          url: v,
          remark: o.optionRemark
        }))];
      }
    });
    const index = details.findIndex(d => d.id === option.id);
    const modal = this.nzModalService.create({
      nzTitle: question.questionName,
      nzContent: PreviewOptionImgRemarkComponent,
      nzComponentParams: {
        details,
        index
      },
      nzFooter: null,
      nzMaskClosable: true,
    });
  }

  // 隐藏选项描述和图片
  hideOptionRemarkModal() {
    this.optionRemark = {
      visible: false,
      title: '',
      option: {
        optionName: '',
        optionRemark: '',
        optionImages: [],
      },
    };
  }

  // 查看图片
  previewImage(src: string) {
    this.nzImageService.preview([{src, width: '400px', height: '400px'}], {nzZoom: 1.5, nzRotate: 0});
  }


  // 离开
  back() {
    this.router.navigate(['/aisi-recyc/assessTypeManageList']);
  }

  // 校验是否有空的特殊设置
  verifyCustom() {
    let includeNUll = false;
    this.customList.forEach(group => {
      group.forEach((c: any) => {
        if (c.usedPriceInfo.price === null || c.newPriceInfo.price === null
          || c.optionRelations.some((o: any) => (!o.questionId || !o.optionId))) {
          includeNUll = true;
        }
      });
    });
    return includeNUll;
  }

  // 校验是否有空的题目价格
  verifyQuestionPrice() {
    let includeNUll = false;
    for (const [key, value] of Object.entries(this.optionsRelationPrice)) {
      // @ts-ignore
      if (value.usedPriceInfo.price === null || value.newPriceInfo.price === null) {
        includeNUll = true;
      }
    }
    return includeNUll;
  }

  // 添加特殊设置的选项关联
  appendOptionRelation(list: any) {
    list.push({questionId: '', optionId: ''});
  }

  relationQuestionChange(customIndex: number, id: any, type = '') {
    if (type === 'fixedPrice') {
      this.fixedPriceList.forEach(c => {
        c.optionRelations.forEach((o: any, index: number) => {
          if (index === customIndex) {
            o.questionId = id;
          }
        });
      });
    } else {
      this.customList.forEach(group => {
        group.forEach((c: any) => {
          c.optionRelations.forEach((o: any, index: number) => {
            if (index === customIndex) {
              o.questionId = id;
            }
          });
        });
      });
    }
  }

  // 可选的的题目
  getRelationQuestions(id: string, type = '') {
    if (type === 'fixedPrice') {
      const disabledIds = this.fixedPriceModal.optionRelations.map((r: any) => r.questionId);
      return disabledIds.includes(id);
    } else {
      const disabledIds = this.customModal.optionRelations.map((r: any) => r.questionId);
      return disabledIds.includes(id);
    }
  }

  // 可选的的选项
  getAvailableOptions(id: string) {
    const disabledIds = this.customModal.optionRelations.map((r: any) => r.optionId);
    return disabledIds.includes(id);
  }

  // 关联的选项
  getRelationOptions(id: string) {
    let list: any[] = [];
    this.questionList.forEach((q: any) => {
      if (q.id === id) {
        list = q.options;
      }
    });
    return list;
  }

  // 设置题目列表
  setQuestionList(id: any) {
    this.questionList = [];
    this.baseQuestion = {
      questionId: '',
      options: []
    };
    this.customList = [];
    this.fixedPriceList = [];
    return this.assessPriceService.getTemplateDetail(id).then((res: any) => {
      if (res.code === 0) {
        this.questionList = JSON.parse(res.data.context);
        this.questionList.forEach((q: any) => {
          this.questionNameList = {...this.questionNameList, [q.id]: q.questionName};
          q.options.forEach((o: any) => {
            this.optionNameList = {...this.optionNameList, [o.id]: o.optionName};
          });
        });
        // questionNameList
        // optionNameList
        this.initOptionsRelationPrice(this.questionList);
        this.setCacheData(id, '');
      }
    });
  }

  // 删除特殊设置的条件
  removeRelationQuestion(relation: any, relationIndex: number) {
    relation.splice(relationIndex, 1);
  }

  // 删除特殊设置
  removeCustom(item: any, customIndex: number) {
    item.splice(customIndex, 1);
    this.calcPrice();
  }

  // 数据完整验证
  fullVerify() {
    if (!this.formData.brand) {
      return '请选择品牌';
    }
    if (!this.formData.department) {
      return '请选择系列';
    }
    if (!this.formData.type) {
      return '请选择机型';
    }
    if (!this.formData.template) {
      return '请选择估价模版';
    }
    if (!this.baseQuestion.questionId) {
      return '请选择基准题目并配置';
    }
    if (this.verifyCustom()) {
      return '存在未填写的特殊设置';
    }
    if (this.verifyQuestionPrice()) {
      return '存在未填写的选项价格';
    }
    return;
  }

  // 保存数据
  submit() {
    const message = this.fullVerify();
    if (message) {
      this.message.warning(message);
      return;
    }
    if (this.baseQuestion.options.some((o: any) => !o.config)) {
      this.message.warning('请确认都已配置并勾选');
      return;
    }
    this.customList = this.customList.filter(value => value.length);
    let newP = 0;
    let usedP = 0;
    this.baseQuestion.options.forEach((o: any) => {
      if (newP < o.newPriceInfo.basePrice) {
        newP = o.newPriceInfo.basePrice;
      }
      if (usedP < o.usedPriceInfo.basePrice) {
        usedP = o.usedPriceInfo.basePrice;
      }
      if (o.id === this.currentOId) {
        o.customList = this.customList;
        o.questionRelation = this.optionsRelationPrice;
        o.fixedPrice = this.fixedPriceList;
      }
    });
    this.formData.newBasePrice = newP;
    this.formData.usedBasePrice = usedP;
    this.assessPriceService.addAndModifyTypeAssess(
      this.formData.newBasePrice,
      this.formData.usedBasePrice,
      this.formData.template,
      this.formData.evaluationId,
      this.formData.remark,
      this.formData.evalStatus,
      JSON.stringify({
        baseQuestion: this.baseQuestion,
        questionIds: this.questionList.map(q => q.id).join(','),
      }),
      this.formData.type,
      this.operationType !== 'modify'
    ).then((res: any) => {
      if (res.code === 0) {
        this.message.success('操作成功');
        this.isSaved = true;
        this.router.navigate(['/aisi-recyc/assessTypeManageList']);
      } else {
        this.message.error(res.message);
      }
    }).catch(() => {
      this.message.error('操作异常');
    });
  }

  // 预览
  previewAssessType() {
    const message = this.fullVerify();
    if (message) {
      this.message.warning(message);
      return;
    }
    this.formData.brandName = this.brandOptions.filter(b => b.id === this.formData.brand)[0].name;
    this.formData.departmentName = this.departmentOptions.filter(b => b.id === this.formData.department)[0].name;
    this.formData.typeName = this.typeOptions.filter(b => b.id === this.formData.type)[0].name;
    this.formData.templateName = this.templateOptions.filter(b => b.id === this.formData.template)[0].title;
    this.previewAssessTypeVisible = true;
  }

  optionClick(id: any, item: any) {
    item.options.forEach((o: any) => {
      if (o.id === id && o.selectAble) {
        o.value = !o.value;
      } else {
        o.value = false;
      }
    });
    this.calcPrice();
  }

  // 一口价计算
  fixedPriceCalc(isNewDevice: boolean, ids: any[]) {
    let result = {isFixedPrice: false, price: 0};
    this.assessPriceText = '';
    let copyFixedPriceList = JSON.parse(JSON.stringify(this.fixedPriceList));
    copyFixedPriceList = copyFixedPriceList.sort((a: any, b: any) => {
      let bp = 0;
      let ap = 0;
      if (isNewDevice) {
        bp = b.newPriceInfo.type === 'fixed' ? b.newPriceInfo.price : this.priceToFloor(this.mABP.basePrice, b.newPriceInfo.price);
        ap = a.newPriceInfo.type === 'fixed' ? a.newPriceInfo.price : this.priceToFloor(this.mABP.basePrice, a.newPriceInfo.price);
      }
      bp = b.usedPriceInfo.type === 'fixed' ? b.usedPriceInfo.price : this.priceToFloor(this.mABP.basePrice, b.usedPriceInfo.price);
      ap = a.usedPriceInfo.type === 'fixed' ? a.usedPriceInfo.price : this.priceToFloor(this.mABP.basePrice, a.usedPriceInfo.price);
      return bp - ap;
    });
    for (let i = 0; i < copyFixedPriceList.length; i++) {
      const optionIds = copyFixedPriceList[i].optionRelations.map((o: any) => o.optionId);
      if (new Set([...optionIds, ...ids]).size === ids.length && ids.length >= 2) {
        const mABP = this.minLimitAndBasePrice(isNewDevice, ids);
        let price: any = 0;
        if (isNewDevice) {
          if (copyFixedPriceList[i].newPriceInfo.type === 'fixed') {
            price = copyFixedPriceList[i].newPriceInfo.price;
          } else if (copyFixedPriceList[i].newPriceInfo.type === 'percentage') {
            price = this.priceToFloor(mABP.basePrice, copyFixedPriceList[i].newPriceInfo.price);
          }
        } else {
          if (copyFixedPriceList[i].usedPriceInfo.type === 'fixed') {
            price = copyFixedPriceList[i].usedPriceInfo.price;
          } else if (copyFixedPriceList[i].usedPriceInfo.type === 'percentage') {
            price = this.priceToFloor(mABP.basePrice, copyFixedPriceList[i].usedPriceInfo.price);
          }
        }
        price = `${isNewDevice ? '预计准新' : '预计二手'}${price < mABP.minPrice ? '保底价格（一口价）：' : '一口价：'}${price < mABP.minPrice ? Math.floor(mABP.minPrice) : Math.floor(price)}`;
        result = {isFixedPrice: true, price};
      }
    }
    return result;
  }

  // 获取保底价格和基准价格
  minLimitAndBasePrice(isNewDevice: boolean, ids: any[]) {
    this.mABP = {
      checked: false,
      minPrice: 0,
      basePrice: 0
    };
    this.baseQuestion.options.forEach((o: any) => {
      if (ids.includes(o.id)) {
        if (isNewDevice) {
          this.mABP.basePrice = o.newPriceInfo.basePrice;
          if (o.newPriceInfo.type === 'fixed') {
            this.mABP.minPrice = o.newPriceInfo.price;
          } else if (o.newPriceInfo.type === 'percentage') {
            this.mABP.minPrice = this.priceToFloor(o.newPriceInfo.basePrice, o.newPriceInfo.price);
          }
        } else {
          this.mABP.basePrice = o.usedPriceInfo.basePrice;
          if (o.usedPriceInfo.type === 'fixed') {
            this.mABP.minPrice = o.usedPriceInfo.price;
          } else if (o.usedPriceInfo.type === 'percentage') {
            this.mABP.minPrice = this.priceToFloor(o.usedPriceInfo.basePrice, o.usedPriceInfo.price);
          }
        }
      }
    });
    return this.mABP;
  }

  calcPrice() {
    if (this.verifyCustom()) {
      this.message.warning('存在未填写的特殊设置');
      return;
    }
    this.isNewDevice = false;
    // 选中的选项结果id
    let ids: any[] = [];
    // 选中的多选id
    const multipleIds: any[] = [];
    // 二手基础价格
    let usedPrice = 0;
    // 准新基础价格
    let newPrice = 0;
    // 展示价格计算结果
    this.assessPriceText = '';
    const copyQuestionList = JSON.parse(JSON.stringify(this.questionList));
    const copyOptionsRelationPrice = JSON.parse(JSON.stringify(this.optionsRelationPrice));
    const copyCustomList = JSON.parse(JSON.stringify(this.customList));
    // 获取选中的选项id添加到ids并判断是否是准新机
    copyQuestionList.forEach((question: any) => {
      if (question.selectType === 0) {
        question.options.forEach((option: any) => {
          // 添加单选选项到ids
          if (option.value) {
            ids.push(option.id);
          }
          if (!option.used && option.value) {
            // 判定为准新机器
            this.isNewDevice = true;
          }
        });
      } else if (question.selectType === 1) {
        // 遍历多选选项
        question.options.forEach((option: any) => {
          // 添加多选选项到ids
          if (option.check) {
            ids.push(option.id);
            multipleIds.push(option.id);
            if (!option.used) {
              // 判定为准新机器
              this.isNewDevice = true;
            }
          }
        });
      }
    });
    this.checkedIds = [...ids, ...multipleIds];
    const result = this.fixedPriceCalc(this.isNewDevice, ids);
    this.fixedPriceResult = result;
    if (result.isFixedPrice) {
      return;
    }
    // 计算特殊设置扣钱金额
    const customResult: any = [];
    const mABP = this.minLimitAndBasePrice(this.isNewDevice, ids);
    if (this.isNewDevice) {
      newPrice = mABP.basePrice;
    } else {
      usedPrice = mABP.basePrice;
    }
    copyCustomList.forEach((group: any) => {
      group.forEach((c: any) => {
        if (c.newPriceInfo.type === 'fixed') {
          c.newPriceInfo.price = -c.newPriceInfo.price;
        } else if (c.usedPriceInfo.type === 'percentage') {
          c.newPriceInfo.price = -this.priceToFloor(mABP.basePrice, c.newPriceInfo.price);
        }
        if (c.usedPriceInfo.type === 'fixed') {
          c.usedPriceInfo.price = -c.usedPriceInfo.price;
        } else if (c.usedPriceInfo.type === 'percentage') {
          c.usedPriceInfo.price = -this.priceToFloor(mABP.basePrice, c.usedPriceInfo.price);
        }
      });
      group = group.sort((a: any, b: any) => {
        if (this.isNewDevice) {
          return a.newPriceInfo.price - b.newPriceInfo.price;
        }
        return a.usedPriceInfo.price - b.usedPriceInfo.price;
      });
      let first = true;
      group.forEach((c: any) => {
        if (first) {
          const options = c.optionRelations.map((o: any) => o.optionId);
          if (ids.length >= 2 && ids.length === new Set([...ids, ...options]).size) {
            first = false;
            customResult.push([c]);
          }
        }
      });
    });
    // 价格计算到结果中
    customResult.forEach((g: any) => {
      if (this.isNewDevice) {
        newPrice += g[0].newPriceInfo.price;
      } else {
        usedPrice += g[0].usedPriceInfo.price;
      }
    });
    // 剔除已经计算过特殊设置了的选项
    const customResultIds = customResult.map((g: any) => g[0].optionRelations.map((o: any) => o.optionId)).flat();
    ids = ids.filter(id => !customResultIds.includes(id) && !multipleIds.includes(id));

    const availableMultipleIds = multipleIds.filter(id => !customResultIds.includes(id));
    ids = [...ids, ...availableMultipleIds];
    ids.forEach(id => {
      // @ts-ignore
      usedPrice += copyOptionsRelationPrice[id].usedPriceInfo.type === 'fixed' ?
        -copyOptionsRelationPrice[id].usedPriceInfo.price :
        -this.priceToFloor(mABP.basePrice, copyOptionsRelationPrice[id].usedPriceInfo.price);
      // @ts-ignore
      newPrice += copyOptionsRelationPrice[id].newPriceInfo.type === 'fixed' ?
        -copyOptionsRelationPrice[id].newPriceInfo.price :
        -this.priceToFloor(mABP.basePrice, copyOptionsRelationPrice[id].newPriceInfo.price);
    });

    if (this.isNewDevice) {
      // @ts-ignore
      this.assessPriceText = `预计准新${newPrice < mABP.minPrice ? '保底价格：' : '价格：'}${newPrice < mABP.minPrice ? Math.floor(mABP.minPrice) : Math.floor(newPrice)}`;
    } else {
      // @ts-ignore
      this.assessPriceText = `预计二手${usedPrice < mABP.minPrice ? '保底价格：' : '价格：'}${usedPrice < mABP.minPrice ? Math.floor(mABP.minPrice) : Math.floor(usedPrice)}`;
    }
  }

  editCustom(item: any, groupIndex: number, groupItemIndex: number) {
    this.customModal.groupIndex = groupIndex;
    this.customModal.groupItemIndex = groupItemIndex;
    this.customModal.optionRelations = JSON.parse(JSON.stringify(item.optionRelations));
    this.customModal.usedPriceInfo = JSON.parse(JSON.stringify(item.usedPriceInfo));
    this.customModal.newPriceInfo = JSON.parse(JSON.stringify(item.newPriceInfo));
    this.customModal.visible = true;
  }

  // 显示特殊设置模态框
  showCustomModal(index: number) {
    if (this.questionList.length < 2) {
      this.message.warning('题目数量小于两个，不能添加特殊设置');
      return;
    }
    this.customModal.visible = true;
    this.customModal.title = '添加特殊设置';
    this.customModal.groupIndex = index;
  }

  // 隐藏特殊设置模态框
  hideCustomModal() {
    this.customModal = {
      visible: false,
      title: '',
      groupIndex: 0,
      groupItemIndex: null,
      // @ts-ignore
      optionRelations: [{questionId: '', optionId: ''}, {questionId: '', optionId: ''}],
      usedPriceInfo: {type: 'percentage', price: 0},
      newPriceInfo: {type: 'percentage', price: 0}
    };
  }

  // 保存特殊设置
  saveCustomModal() {
    if (this.customModal.optionRelations.some((r: any) => !r.questionId)) {
      this.message.warning('请选择题目');
      return;
    }
    if (this.customModal.optionRelations.some((r: any) => !r.optionId)) {
      this.message.warning('请选择选项');
      return;
    }
    if (this.customModal.usedPriceInfo.price === null || !this.customModal.usedPriceInfo.price.toString().length) {
      this.message.warning('请输入二手扣钱信息');
      return;
    }
    if (this.customModal.newPriceInfo.price === null || !this.customModal.newPriceInfo.price.toString().length) {
      this.message.warning('请输入准新扣钱信息');
      return;
    }
    let multipleC: any = null;
    let multipleF: any = null;
    const fList = new Set(this.customModal.optionRelations.map((i: any) => i.questionId + '-' + i.optionId));
    this.fixedPriceList.forEach((c, index) => {
      const cList = c.optionRelations.map((i: any) => i.questionId + '-' + i.optionId);
      const set1 = new Set(fList);
      const set2 = new Set(cList);
      const set3 = new Set([...fList, ...cList]);
      if (set1.size === set2.size && set1.size === set3.size) {
        multipleF = index;
      }
    });
    this.customList.forEach((group, gIndex) => {
      group.forEach((c: any, index: number) => {
        const cList = c.optionRelations.map((i: any) => i.questionId + '-' + i.optionId);
        const set1 = new Set(fList);
        const set2 = new Set(cList);
        const set3 = new Set([...fList, ...cList]);
        if (set1.size === set2.size && set1.size === set3.size) {
          multipleC = gIndex + '-' + index;
        }
      });
    });
    if (multipleF !== null) {
      this.message.warning('当前条件已存在一口价，无法保存');
      return;
    }
    if (multipleC !== null && (this.customModal.groupIndex + '-' + this.customModal.groupItemIndex) !== multipleC) {
      this.message.warning('特殊设置已包含有当前条件，无法保存，请先删除冲突的特殊设置');
      return;
    }
    if (this.customModal.groupItemIndex === null) {
      this.customList[this.customModal.groupIndex].push({
        optionRelations: JSON.parse(JSON.stringify(this.customModal.optionRelations)),
        usedPriceInfo: JSON.parse(JSON.stringify(this.customModal.usedPriceInfo)),
        newPriceInfo: JSON.parse(JSON.stringify(this.customModal.newPriceInfo)),
      });
    } else {
      this.customList[this.customModal.groupIndex][this.customModal.groupItemIndex].optionRelations = JSON.parse(JSON.stringify(this.customModal.optionRelations));
      this.customList[this.customModal.groupIndex][this.customModal.groupItemIndex].usedPriceInfo = JSON.parse(JSON.stringify(this.customModal.usedPriceInfo));
      this.customList[this.customModal.groupIndex][this.customModal.groupItemIndex].newPriceInfo = JSON.parse(JSON.stringify(this.customModal.newPriceInfo));
    }
    this.hideCustomModal();
    this.calcPrice();
  }

  editFixedPrice(data: any, index: number) {
    this.fixedPriceModal.optionRelations = JSON.parse(JSON.stringify(data.optionRelations));
    this.fixedPriceModal.usedPriceInfo = JSON.parse(JSON.stringify(data.usedPriceInfo));
    this.fixedPriceModal.newPriceInfo = JSON.parse(JSON.stringify(data.newPriceInfo));
    this.fixedPriceModal.editIndex = index;
    this.showFixedPriceModal();
  }

  // 显示一口价模态框
  showFixedPriceModal() {
    if (this.questionList.length < 2) {
      this.message.warning('题目数量小于两个，不能添加特殊设置');
      return;
    }
    this.fixedPriceModal.visible = true;
  }

  // 隐藏一口价模态框
  hideFixedPriceModal() {
    this.fixedPriceModal = {
      visible: false,
      title: '',
      optionRelations: [{questionId: '', optionId: ''}, {questionId: '', optionId: ''}],
      usedPriceInfo: {type: 'percentage', price: 0},
      newPriceInfo: {type: 'percentage', price: 0},
      editIndex: null,
    };
  }

  saveFixedPriceModal() {
    if (this.fixedPriceModal.optionRelations.some((r: any) => !r.questionId)) {
      this.message.warning('请选择题目');
      return;
    }
    if (this.fixedPriceModal.optionRelations.some((r: any) => !r.optionId)) {
      this.message.warning('请选择选项');
      return;
    }
    if (this.fixedPriceModal.usedPriceInfo.price === null || !this.fixedPriceModal.usedPriceInfo.price.toString().length) {
      this.message.warning('请输入二手一口价信息');
      return;
    }
    if (this.fixedPriceModal.newPriceInfo.price === null || !this.fixedPriceModal.newPriceInfo.price.toString().length) {
      this.message.warning('请输入准新一口价信息');
      return;
    }
    let multipleC: any = null;
    let multipleF: any = null;
    const fList = new Set(this.fixedPriceModal.optionRelations.map((i: any) => i.questionId + '-' + i.optionId));
    this.customList.forEach(group => {
      group.forEach((c: any) => {
        const cList = c.optionRelations.map((i: any) => i.questionId + '-' + i.optionId);
        const set1 = new Set(fList);
        const set2 = new Set(cList);
        const set3 = new Set([...fList, ...cList]);
        if (set1.size === set2.size && set1.size === set3.size) {
          multipleC = c;
        }
      });
    });
    this.fixedPriceList.forEach((c, index) => {
      const cList = c.optionRelations.map((i: any) => i.questionId + '-' + i.optionId);
      const set1 = new Set(fList);
      const set2 = new Set(cList);
      const set3 = new Set([...fList, ...cList]);
      if (set1.size === set2.size && set1.size === set3.size) {
        multipleF = index;
      }
    });
    if (multipleF !== null && multipleF !== this.fixedPriceModal.editIndex) {
      this.message.warning('当前条件已存在一口价，无法保存');
      return;
    }
    if (multipleC !== null) {
      this.message.warning('特殊设置已包含有当前条件，无法保存，请先删除冲突的特殊设置');
      return;
    }
    if (this.fixedPriceModal.editIndex === null) {
      this.fixedPriceList.push({
        optionRelations: this.fixedPriceModal.optionRelations,
        usedPriceInfo: this.fixedPriceModal.usedPriceInfo,
        newPriceInfo: this.fixedPriceModal.newPriceInfo,
      });
    } else {
      this.fixedPriceList[this.fixedPriceModal.editIndex].optionRelations = this.fixedPriceModal.optionRelations;
      this.fixedPriceList[this.fixedPriceModal.editIndex].usedPriceInfo = this.fixedPriceModal.usedPriceInfo;
      this.fixedPriceList[this.fixedPriceModal.editIndex].newPriceInfo = this.fixedPriceModal.newPriceInfo;
    }
    this.hideFixedPriceModal();
    this.calcPrice();
  }

  addCustomGroup() {
    this.customList.push([]);
  }

  initPrice(item: any) {
    item.price = 0;
  }

  priceToFloor(price: any, percent = 100) {
    return price * percent / 100;
  }

  filterJumpQuestion() {
    const index = this.questionList.findIndex(q => q.options.filter((option: any) => option?.questionId).length);
    return this.questionList.slice(0, index !== -1 ? index : this.questionList.length);
  }

  // 特殊设置选中
  customSelect(groupIndex: number, customIndex: number, group: any) {
    // 之前选中的选项id
    const gOldOId: any[] = [];
    Object.entries(this.selectedCustom).forEach(([key, value]) => {
      if (value) {
        this.customList.forEach((g, gIndex) => {
          g.forEach((item: any, itemIndex: number) => {
            if (key === (gIndex + '-' + itemIndex)) {
              gOldOId.push(...item.optionRelations.map((r: any) => r.optionId));
            }
          });
        });
      }
    });
    if (this.selectedCustom[groupIndex + '-' + customIndex] === undefined) {
      this.selectedCustom[groupIndex + '-' + customIndex] = true;
    } else {
      this.selectedCustom[groupIndex + '-' + customIndex] = !this.selectedCustom[groupIndex + '-' + customIndex];
    }
    Object.entries(this.selectedCustom).forEach(([key, value]) => {
      if (key !== (groupIndex + '-' + customIndex)) {
        this.selectedCustom[key] = false;
      }
    });
    const gOId = group.optionRelations.map((r: any) => r.optionId);
    this.questionList.forEach(q => {
      q.options.forEach((o: any) => {
        if (q.selectType === 0) {
          // 单选
          if (gOldOId.includes(o.id)) {
            o.value = false;
          }
          if (gOId.includes(o.id) && o.selectAble) {
            q.options.forEach((oo: any) => oo.value = false);
            o.value = this.selectedCustom[groupIndex + '-' + customIndex];
          }
        } else {
          // 多选
          if (gOldOId.includes(o.id)) {
            o.check = false;
          }
          if (gOId.includes(o.id)) {
            o.check = this.selectedCustom[groupIndex + '-' + customIndex];
          }
        }
      });
    });
    this.calcPrice();
  }

  // 一口价选中
  fixedPriceSelect(index: number, group: any) {
    // 之前选中的选项id
    const gOldOId: any[] = [];
    Object.entries(this.selectedFixedPrice).forEach(([key, value]) => {
      if (value) {
        gOldOId.push(...this.fixedPriceList[parseInt(key, 10)].optionRelations.map((r: any) => r.optionId));
      }
    });
    if (this.selectedFixedPrice[index] === undefined) {
      this.selectedFixedPrice[index] = true;
    } else {
      this.selectedFixedPrice[index] = !this.selectedFixedPrice[index];
    }
    Object.entries(this.selectedFixedPrice).forEach(([key, value]) => {
      if (parseInt(key, 10) !== index) {
        this.selectedFixedPrice[key] = false;
      }
    });
    const gOId = group.optionRelations.map((r: any) => r.optionId);
    this.questionList.forEach(q => {
      q.options.forEach((o: any) => {
        if (q.selectType === 0) {
          // 单选
          if (gOldOId.includes(o.id)) {
            o.value = false;
          }
          if (gOId.includes(o.id) && o.selectAble) {
            q.options.forEach((oo: any) => oo.value = false);
            o.value = this.selectedFixedPrice[index];
          }
        } else {
          // 多选
          if (gOldOId.includes(o.id)) {
            o.check = false;
          }
          if (gOId.includes(o.id)) {
            o.check = this.selectedFixedPrice[index];
          }
        }
      });
    });
    this.calcPrice();
  }

  showCopyOptionModal() {
    this.copyOptionModal.visible = true;
  }

  hideCopyOptionModal() {
    this.copyOptionModal = {
      visible: false,
      optionId: ''
    };
  }

  saveCopyOptionModal() {
    this.baseQuestion.options.forEach((o: any) => {
      if (o.id === this.copyOptionModal.optionId) {
        if (o.questionRelation) {
          this.optionsRelationPrice = JSON.parse(JSON.stringify(o.questionRelation));
        } else {
          this.initOptionsRelationPrice(this.questionList);
        }
        this.customList = JSON.parse(JSON.stringify(o.customList)) || [];
        this.fixedPriceList = JSON.parse(JSON.stringify(o.fixedPrice)) || [];
      }
    });
    this.modifyCustomOptionColor = [];
    this.hideCopyOptionModal();
  }
}
